package com.qf.web.controller;

import com.qf.domain.Goods;
import com.qf.domain.GoodsType;
import com.qf.domain.PageBean;
import com.qf.domain.User;
import com.qf.service.GoodTypeService;
import com.qf.service.GoodsService;
import com.qf.service.impl.GoodTypeServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/goodsservlet")
@MultipartConfig(maxFileSize = 5*1024*1024,maxRequestSize = 20*1024*1024) /*因为有文件上传所以必须有这个注解*/
public class GoodsServlet extends BaseServlet {
    /*分页查询 typeid类型  id查询*/
    //http://localhost:8080/goodsservlet?method=getGoodsListByTypeId&typeId=1
    public String getGoodsListByTypeId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获取前端数据
        //商品类别
        String typeId = request.getParameter("typeId");
        //商品名称
        String goodsName = request.getParameter("goodsName");
        //商品页面
        String pageNum = request.getParameter("pageNum");
        //页大小
        String pageSize = request.getParameter("pageSize");
        //校验
        int page_num = 1;
        int page_size = 8;
        try { //这里类型格式化了所以异常处理
            if (!StringUtils.isEmpty(pageNum)) {
                page_num = Integer.parseInt(pageSize);
                if(page_num<1){
                    page_num=1;
                }
            }
            if(!StringUtils.isEmpty(pageSize)){
                page_size=Integer.parseInt(pageSize);
                if(page_size<1){
                    page_size=8;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //封装条件 //因为多条件查询么
        StringBuilder where = new StringBuilder(" where 1=1 ");//这里两边空白是因为sql语句要拼接所以空白分开关键字
        List<Object> params = new ArrayList<Object>();
        if(!StringUtils.isEmpty(typeId)){
            where.append(" and typeid=? ");
            params.add(typeId);
        }
        if (!StringUtils.isEmpty(goodsName)) {
            where.append(" and name like ? ");
            params.add("%"+goodsName+"%");
        }

        //如果没有条件
        if (params.size()<=0) {
            return "/goodsList.jsp";
        }
        //调用业务逻辑
        try {
            GoodsService goodsService = new GoodsServiceImpl();
            PageBean<Goods> pageBean=goodsService.findByPage(page_num,page_size,where.toString(),params); //StringBuilder类型所以toString
            System.out.println("pageBean = " + pageBean);//没有数据后台的问题，控制台有数据，前端不显示是前端的问题
            //存数据
            request.setAttribute("typeId",typeId);
            request.setAttribute("goodsName",goodsName);
            request.setAttribute("pageBean",pageBean);
            return "/goodsList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/index.jsp";
    }


    /*通过id 查找商品信息*/
     //http://localhost:8080/goodsservlet?method=getGoodsById&id=1
     public String getGoodsById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //获取前端数据
         String id = request.getParameter("id");
         System.out.println("id = " + id);
         //非空验证
         if (StringUtils.isEmpty(id)) {
             request.setAttribute("msg","商品id不能为空");
             return "/message.jsp";
         }
         //调用业务逻辑
         try {
             GoodsService goodService = new GoodsServiceImpl();
             Goods goods  = goodService.findById(Integer.parseInt(id));
             request.setAttribute("goods",goods);//存一下
             //转发重定向
             return "/goodsDetail.jsp";

         } catch (NumberFormatException e) {
             request.setAttribute("msg","查询失败"+e.getMessage());
             return "/message.jsp";
         }
     }

     /*管理员添加商品信息*/
     ///goodsservlet?method=addGoods
     public String addGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         response.setContentType("text/html;charset=UTF-8");
         //1判断是否登录 admin
         User admin = (User)request.getSession().getAttribute("admin");
         if (admin == null) {
             return "redirect:/admin/login.jsp";
         }
         //2获取前端数据
         String name = request.getParameter("name");
         String typeid = request.getParameter("typeid");
         String pubdate = request.getParameter("pubdate");
         String price = request.getParameter("price");
         String star = request.getParameter("star");
         String intro = request.getParameter("intro");
         //获取图片
         Part picture = request.getPart("picture");
         //非空验证
         if(StringUtils.isEmpty(name)){
             request.setAttribute("msg","商品名称不能为空");
             return "/admin/addGoods.jsp";
         }
         if(StringUtils.isEmpty(typeid)){
             request.setAttribute("msg","商品类型不能为空");
             return "/admin/addGoods.jsp";
         }
         if(StringUtils.isEmpty(pubdate)){
             request.setAttribute("msg","商品上架时间不能为空");
             return "/admin/addGoods.jsp";
         }
         if(StringUtils.isEmpty(price)){
             request.setAttribute("msg","商品价格不能为空");
             return "/admin/addGoods.jsp";
         }
         if(StringUtils.isEmpty(star)){
             request.setAttribute("msg","商品热销指数不能为空");
             return "/admin/addGoods.jsp";
         }
         if(StringUtils.isEmpty(intro)){
             request.setAttribute("msg","商品详情不能为空");
             return "/admin/addGoods.jsp";
         }
         //调用业务逻辑
         int type_id = Integer.parseInt(typeid);
         if (type_id<=0) {
             request.setAttribute("msg","请选择合适类型");
             return "/admin/addGoods.jsp";
         }
          //处理图片
         //IE浏览器路径 文件名问题
         String dis = picture.getHeader("Content-Disposition");
         String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);//D:\bookcover\101.jpg
         filename = filename.substring(filename.lastIndexOf("\\") + 1);
         String uuidFileName=null;
         if (!filename.equals("")) {//文件名不为空上传图片
             //保存图片
             String basePath = this.getServletContext().getRealPath("WEB-INF" + File.separator + "images");//基本目录
             File dir = new File(basePath);
             if (!dir.exists()) {
                 dir.mkdirs();//基本目录不存在创建多级目录
             }
             //获取后缀
             String ext = filename.substring(filename.lastIndexOf(".")+1);
             uuidFileName = UUID.randomUUID().toString().replace("-","");
             uuidFileName=uuidFileName+"."+ext;
             picture.write(basePath+File.separator+uuidFileName);
             picture.delete();
             System.out.println("保存图片成功");
         }
         //调用业务逻辑
         try {
             GoodsService goodsService = new GoodsServiceImpl();
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
             Goods goods = new Goods(0,name,sdf.parse(pubdate),uuidFileName,new BigDecimal(price),Integer.parseInt(star),intro,type_id);
             goodsService.add(goods);
             response.getWriter().write("<script>alert('添加成功');window.location='admin/addGoods.jsp';</script>");
         } catch (Exception e) {
             e.printStackTrace();
             response.getWriter().write("<script>alert('添加失败');window.location='admin/addGoods.jsp';</script>");
         }
         return null;
     }
    public String showAllGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
        GoodsService goodsService=new GoodsServiceImpl();
        List<Goods> goods= goodsService.findAll();

        GoodTypeService goodTypeService=new GoodTypeServiceImpl();
        List<GoodsType> goodsTypes = goodTypeService.findAll();
        request.setAttribute("goodsTypeList",goodsTypes);
        request.setAttribute("goodsList",goods);
        return "/admin/showGoods.jsp";
    }
    public String deleteGoods(HttpServletRequest request, HttpServletResponse response)throws Exception
    {
        String gid = request.getParameter("id");
        GoodsService goodsService=new GoodsServiceImpl();
        goodsService.deleteById(gid);
        List<Goods> goods= goodsService.findAll();
        request.setAttribute("goodsList",goods);
        return "/admin/showGoods.jsp";
    }
    public String updateGoods(HttpServletRequest request, HttpServletResponse response)throws Exception
    {
        //理论来说必须全部赋值介绍没有也应给个无
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String goodsType = request.getParameter("goodsType");
        String intro = request.getParameter("intro");
        String star=request.getParameter("star");
        Part picture = request.getPart("picture");
        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);//D:\bookcover\101.jpg
        filename = filename.substring(filename.lastIndexOf("\\") + 1);
        String uuidFileName=null;
        if (!filename.equals("")) {//文件名不为空上传图片
            //保存图片
            String basePath = this.getServletContext().getRealPath("WEB-INF" + File.separator + "images");
            File dir=new File(basePath);
            if (!dir.exists()) {
                dir.mkdirs();//创建多级目录
            }
            //获取后缀
            String ext=filename.substring(filename.lastIndexOf(".")+1);
            uuidFileName= UUID.randomUUID().toString().replace("-","");
            uuidFileName=uuidFileName+"."+ext;
            picture.write(basePath+File.separator+uuidFileName);
            picture.delete();
            System.out.println("保存图片成功");
        }
        Goods goods=new Goods(Integer.parseInt(id),name,new Date(),uuidFileName,new BigDecimal(price),Integer.parseInt(star),intro,Integer.parseInt(goodsType));
        GoodsService goodsService=new GoodsServiceImpl();
        goodsService.update(goods);
        List<Goods> goods1= goodsService.findAll();
        request.setAttribute("goodsList",goods1);
        return "/admin/showGoods.jsp";
    }
    public String searchGoods(HttpServletRequest request, HttpServletResponse response)throws Exception
    {
        StringBuilder where1=new StringBuilder(" where 1=1 ");
        String username = request.getParameter("sname");
        String pubdate = request.getParameter("spubdate");
        List<Object> I=new ArrayList();
        if (!StringUtils.isEmpty(username))
        {
            where1.append(" and name like ? ");
            I.add("%"+username+"%");
        }
        if (!StringUtils.isEmpty(pubdate))
        {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Date parse = sdf.parse(pubdate);
            where1.append(" and pubdate = ? ");
            I.add(parse);
        }
        GoodsService goodsService=new GoodsServiceImpl();
        List<Goods> goodsList= goodsService.selectByUAD(where1,I);
        request.setAttribute("goodsList",goodsList);
        GoodTypeService goodTypeService=new GoodTypeServiceImpl();
        List<GoodsType> goodsTypes = goodTypeService.findAll();
        request.setAttribute("goodsTypeList",goodsTypes);
        return "/admin/showGoods.jsp";
    }

}




